package com.shwread.android.qysw.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.NewActionHelp;
import com.ciko.code.logic.bean.ContactBookInfo;
import com.ciko.code.logic.dao.ContactBookInfoDao;
import com.google.gson.reflect.TypeToken;
import com.netease.nim.demo.session.model.MsgListItem;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.ImageAttachment;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.widget.sortlistview.CharacterParser;
import com.shwread.android.ui.widget.sortlistview.ClearEditText;
import com.shwread.android.ui.widget.sortlistview.PinyinComparator;
import com.shwread.android.ui.widget.sortlistview.SideBar;
import com.shwread.android.ui.widget.sortlistview.SideBar.OnTouchingLetterChangedListener;
import com.shwread.android.ui.widget.sortlistview.SortAdapter;
import com.shwread.android.ui.widget.sortlistview.SortAdapter.onClickMember;
import com.shwread.android.ui.widget.sortlistview.SortModel;
import com.shwread.http.base.Log;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.http.util.JSONUtil;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import logic.bean.ContactInfo;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.FileUtil;
import logic.util.Util;
import logic.util.Utils;


/**
 * 创建群 联系人选择
 *
 * @author xuzhijun
 * @date 2015年5月22日 上午10:43:43
 */
public class NewInteractionCreateTeamChMActivity
        extends
        BaseSimpleActivity
        implements
        OnClickListener {
    private Context context;

    private String mIniSelectedCids;
    public static final String KEY_CID = "cid";
    public static final String KEY_NAME = "name";
    public static final String KEY_SELECTED = "selected";

    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;
    private SortAdapter adapter;
    private ClearEditText mClearEditText;

    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    //Title
    private TextView tvTitle;
    private Button btnBack;
    private TextView btnSubmit;

    private String todo = "";
    private String teamId = "";
    private MsgListItem selectedItem = null;

    private List<ContactInfo> contactInfos = new ArrayList<ContactInfo>();
    private View choseAllView;
    private CheckBox checkAll;
    //	private RelativeLayout        rlGroup;

    private ContactBookInfoDao addressBookInfoDao;
    private List<ContactBookInfo> dbdatas = new ArrayList<ContactBookInfo>();

    private File file = null;
    private String accId = "";
    //	private int                   isDownLoaded = 0;                               //1:下载完成 0:下载未完成 -1:下载失败
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //			                                           Bundle bundle = msg.getData();
            switch (msg.what) {
                case 1:
                    //															   String accId = bundle.getString("id");
                    IMMessage message = MessageBuilder.createImageMessage(accId, SessionTypeEnum.P2P, file, null);
                    NIMClient.getService(MsgService.class).sendMessage(message, false);
                    Toast.makeText(context, "转发成功", Toast.LENGTH_LONG).show();
                    break;
                case -1:
                    Toast.makeText(context, "转发失败", Toast.LENGTH_LONG).show();
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_interaction_create_team_chose_munber);
        context = this;
        addressBookInfoDao = ContactBookInfoDao.getInstance(context);
        todo = getIntent().getStringExtra(DefaultConsts.NI_CONTACT_INTENT);
        selectedItem = (MsgListItem) getIntent().getSerializableExtra("message");
        teamId = getIntent().getStringExtra("teamId");
        mIniSelectedCids = getIntent().getStringExtra(KEY_SELECTED);
        if (TextUtils.isEmpty(todo) || addressBookInfoDao.getAll() == null) {
            finish();
            return;
        }

        initViews();
        initData();
    }

    private void initViews() {
        //Title
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setVisibility(View.VISIBLE);
        if (todo.equals(DefaultConsts.NI_CONTACT_FORWARD) || todo.equals(DefaultConsts.NI_CONTACT_GET_MEMBER)) {
            tvTitle.setText("选择联系人");
        } else {
            tvTitle.setText("选择人员");
        }
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
        btnBack.setOnClickListener(this);
        btnSubmit = (TextView) findViewById(R.id.common_header_create_team);
        if (todo.equals(DefaultConsts.NI_CONTACT_FORWARD) || todo.equals(DefaultConsts.NI_CONTACT_GET_MEMBER)) {
            btnSubmit.setVisibility(View.GONE);
        } else if (todo.equals(DefaultConsts.NI_CONTACT_CREATE_TEAM)) {
            btnSubmit.setVisibility(View.VISIBLE);
            btnSubmit.setText("创建");
        } else {
            btnSubmit.setVisibility(View.VISIBLE);
            btnSubmit.setText("保存");
        }
        //		btnSubmit.setText(getButtonLable());

        btnSubmit.setOnClickListener(this);
        if (todo.equals(DefaultConsts.NI_CONTACT_FORWARD)) {
            choseAllView = LayoutInflater.from(context).inflate(R.layout.chat_forward_list_header, null);
            choseAllView.findViewById(R.id.rl_chat_groups).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent groupIntent = new Intent(NewInteractionCreateTeamChMActivity.this, ContactGroupActivity.class);
                    groupIntent.putExtra("fromType", "forward");
                    groupIntent.putExtra("message", selectedItem);
                    startActivity(groupIntent);
                    finish();
                }
            });
        } else {
            // 实例化汉字转拼音类
            choseAllView = LayoutInflater.from(context).inflate(R.layout.new_interaction_create_team_chose_item, null);
            choseAllView.findViewById(R.id.catalog).setVisibility(View.GONE);
            checkAll = (CheckBox) choseAllView.findViewById(R.id.title);
            checkAll.setText("全部");
        }
        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);
        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                if (adapter != null) {
                    int position = adapter.getPositionForSection(s.charAt(0));
                    if (position != -1) {
                        sortListView.setSelection(position);
                    }
                }

            }
        });

        sortListView = (ListView) findViewById(R.id.country_lvcountry);
        sortListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 这里要利用adapter.getItem(position)来获取当前position所对应的对象
                Toast.makeText(getApplication(), ((SortModel) adapter.getItem(position)).getName(), Toast.LENGTH_SHORT).show();
            }
        });
        if (!todo.equals(DefaultConsts.NI_CONTACT_GET_MEMBER)) {
            sortListView.addHeaderView(choseAllView);
        }
        mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);

        // 根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /**
     * 为ListView填充数据
     *
     * @param
     * @return
     */
    private List<ContactInfo> filledData(List<ContactInfo> contacts) {
        List<ContactInfo> mSortList = new ArrayList<ContactInfo>();
        String pinyin = "";
        for (int i = 0; i < contacts.size(); i++) {
            ContactInfo sortModel = contacts.get(i);
            // 汉字转换成拼音
            if (Util.isNotEmpty(contacts.get(i).getStaffName())) {
                pinyin = characterParser.getSelling(contacts.get(i).getStaffName());
            } else if (Util.isNotEmpty(contacts.get(i).getNickName())) {
                pinyin = characterParser.getSelling(contacts.get(i).getNickName());
            } else {
                pinyin = characterParser.getSelling(contacts.get(i).getAccount());
            }
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (pinyin != null && sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<ContactInfo> filterDateList = new ArrayList<ContactInfo>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = contactInfos;
            choseAllView.setVisibility(View.VISIBLE);
            choseAllView.setPadding(0, 0, 0, 0);
        } else {
            choseAllView.setVisibility(View.GONE);
            if (choseAllView.getHeight() > 0) {
                choseAllView.setPadding(0, -choseAllView.getHeight(), 0, 0);
            }
            filterDateList.clear();
            for (ContactInfo sortModel : contactInfos) {
                String name = "";
                //				= Util.isEmpty(sortModel.getNickName()) ? sortModel.getAccount() : sortModel.getNickName();
                if (Util.isNotEmpty(sortModel.getStaffName())) {
                    name = sortModel.getStaffName();
                } else if (Util.isNotEmpty(sortModel.getNickName())) {
                    name = sortModel.getNickName();
                } else {
                    name = sortModel.getAccount();
                }
                if (name.toLowerCase().indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(contactInfos, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

    private void initData() {
        pinyinComparator = new PinyinComparator();
        characterParser = CharacterParser.getInstance();
        if (todo.equals(DefaultConsts.NI_CONTACT_GET_MEMBER)) {
            //@群成员
            NewActionHelp.qryMemberListByTeamId(context, teamId, new GetMemberHandler());
        } else if (todo.equals(DefaultConsts.NI_CONTACT_FORWARD) || todo.equals(DefaultConsts.NI_CONTACT_CREATE_TEAM) || todo.equals(DefaultConsts.NI_CONTACT_CHOSE_MUNBER))//转发,建群,添加群成员
        {
            //调数据库取联系人列表
            getDataFromDB();
            contactInfos = filledData(contactInfos);
            Collections.sort(contactInfos, pinyinComparator);
            for (int i = 0; i < contactInfos.size() - 1; i++) {
                if (contactInfos.get(i).getStaffName().equals(contactInfos.get(i + 1).getStaffName())) {
                    contactInfos.remove(i);
                    i--;
                }
            }
            if (todo.equals(DefaultConsts.NI_CONTACT_FORWARD)) {
                adapter = new SortAdapter(NewInteractionCreateTeamChMActivity.this, contactInfos, checkAll, new onClickMember() {
                    @Override
                    public void onClick(ContactInfo contactInfo) {
                        ImageAttachment attachment = (ImageAttachment) selectedItem.getMessage().getAttachment();
                        if (Utils.isNotEmpty(attachment.getUrl())) {
                            file = downUrlTxt(attachment.getUrl(), FileUtil.ImageSavePath());
                        } else {
                            file = downUrlTxt(attachment.getPath(), FileUtil.ImageSavePath());
                        }
                        accId = contactInfo.getAccId();
                        //						IMMessage message = MessageBuilder.createImageMessage(contactInfo.getAccId(), SessionTypeEnum.P2P, file, null);
                        //						NIMClient.getService(MsgService.class).sendMessage(message, false);
                        //					MsgListItem item = new MsgListItem(message);
                        //						P2PMessageActivity.start(context, contactInfo.getAccId(), contactInfo.getStaffName());
                        finish();
                    }
                }, 2);
            } else {
                adapter = new SortAdapter(NewInteractionCreateTeamChMActivity.this, contactInfos, checkAll, null, 1);
            }
            sortListView.setAdapter(adapter);
        } else {
            NewActionHelp.qryMyContactWithBoss(this, new MyContactHandler());
        }

    }

    public File downUrlTxt(final String fileUrl, String downPath) {
        final File savePath = new File(downPath);

        if (!savePath.exists()) {
            savePath.mkdir();
        }
        String[] urlname = fileUrl.split("/");
        int len = urlname.length - 1;
        final String uname = urlname[len];//获取文件名
        final File file1 = new File(savePath + "/" + uname + ".png");//创建新文件  ;
        new Thread() {
            @Override
            public void run() {
                try {
                    //					file = new File(savePath + "/" + uname + ".png");//创建新文件
                    if (file1 != null && !file1.exists()) {
                        file1.createNewFile();
                    }
                    OutputStream oputstream = new FileOutputStream(file1);
                    URL url = new URL(fileUrl);
                    HttpURLConnection uc = (HttpURLConnection) url.openConnection();
                    uc.setRequestMethod("GET");
                    uc.setConnectTimeout(5 * 1000);
                    uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true
                    uc.connect();
                    InputStream iputstream = uc.getInputStream();
                    //			System.out.println("file size is:" + uc.getContentLength());//打印文件长度
                    byte[] buffer = new byte[4 * 1024];
                    int byteRead = -1;
                    while ((byteRead = (iputstream.read(buffer))) != -1) {
                        oputstream.write(buffer, 0, byteRead);
                    }
                    oputstream.flush();
                    iputstream.close();
                    oputstream.close();
                    Message msg = Message.obtain();
                    msg.what = 1;
                    myHandler.sendMessage(msg);
                } catch (Exception e) {
                    System.out.println("读取失败！");
                    Message msg = Message.obtain();
                    msg.what = -1;
                    myHandler.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        }.start();

        return file1;
    }

    private void getDataFromDB() {
        ArrayList<String> accIdList = getIntent().getStringArrayListExtra("accIdList");
        if (accIdList == null) {
            accIdList = new ArrayList<>();
        }
        dbdatas = addressBookInfoDao.getAll();
        for (ContactBookInfo info : dbdatas) {
            if (info.getIsDelete().equals("n")
                    && !info.getUserId().equals("0")
                    && !info.getAccId().equals(Const.UserAccId)
                    &&!accIdList.contains(info.getAccId())) {
                ContactInfo contact = new ContactInfo();
                contact.setAccId(info.getAccId());
                contact.setAccount(info.getMobileNumber());
                contact.setHeadImage(info.getUserHead());
                contact.setStaffName(info.getContactName());
                //				contact.setUserId(info.getUserId());
                contact.setStaffId(info.getUserId());
                contactInfos.add(contact);
            }
        }
    }

    private class MyContactHandler
            extends
            ObjectHttpResponseHandler<List<ContactInfo>> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (statusCode > 999) {
                try {
                    Util.ToastShow(context, JSONUtil.getString(responseString));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Util.ToastShow(context, "数据解析失败");
                Log.i(throwable.toString());
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, List<ContactInfo> object, String responseString) {
            // 根据a-z进行排序源数据
            if (object.size() > 0) {
                contactInfos = filledData(object);
                Collections.sort(contactInfos, pinyinComparator);
                adapter = new SortAdapter(NewInteractionCreateTeamChMActivity.this, contactInfos, checkAll, null, 1);
                sortListView.setAdapter(adapter);
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<List<ContactInfo>>() {
            }.getType();
        }

    }

    private class GetMemberHandler
            extends
            ObjectHttpResponseHandler<List<ContactInfo>> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (statusCode > 999) {
                try {
                    Util.ToastShow(context, JSONUtil.getString(responseString));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Util.ToastShow(context, "数据解析失败");
                Log.i(throwable.toString());
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, List<ContactInfo> object, String responseString) {
            // 根据a-z进行排序源数据
            if (object.size() > 0) {
                contactInfos = filledData(object);
                Collections.sort(contactInfos, pinyinComparator);
                adapter = new SortAdapter(NewInteractionCreateTeamChMActivity.this, contactInfos, checkAll, new onClickMember() {
                    @Override
                    public void onClick(ContactInfo contactInfo) {
                        String name = "";
                        if (!Utils.isEmpty(contactInfo.getStaffName())) {
                            name = contactInfo.getStaffName();
                        } else if (!Utils.isEmpty(contactInfo.getNickName())) {
                            name = contactInfo.getNickName();
                        } else {
                            name = contactInfo.getAccount();
                        }
                        Intent intent = new Intent();
                        intent.putExtra(DefaultConsts.TEAM_STAFFNAME, name);
                        //						intent.putExtra(DefaultConsts.TEAM_NICKNAME, contactInfo.getNickName());
                        //						intent.putExtra(DefaultConsts.TEAM_ACCOUNT, contactInfo.getAccount());
                        intent.putExtra(KEY_CID, contactInfo.getAccId());
                        intent.putExtra(KEY_NAME, "@" + name + " ");
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    }
                }, 2);
                sortListView.setAdapter(adapter);
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<List<ContactInfo>>() {
            }.getType();
        }

    }

    private String getButtonLable() {
        String lable = "保存";
        if (TextUtils.isEmpty(todo)) return lable;
        if (todo.equals(DefaultConsts.NI_CONTACT_CREATE_TEAM)) {
            lable = "保存";
        } else if (todo.equals(DefaultConsts.NI_CONTACT_CHOSE_MUNBER)) {
            lable = "添加";
        }
        return lable;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                finish();
                break;
            case R.id.common_header_create_team:
                if (todo.equals(DefaultConsts.NI_CONTACT_CREATE_TEAM)) {
                    create();
                } else if (todo.equals(DefaultConsts.NI_CONTACT_CHOSE_MUNBER)) {
                    add();
                }
                break;
        }

    }

    /**
     * 添加群成员
     */
    private void add() {
        if (adapter.getSelectUids().size() > 0) {
            ArrayList<String> ids = new ArrayList<String>();
            for (int i = 0; i < adapter.getSelectUids().size(); i++) {
                ids.add(adapter.getSelectUids().get(i).getStaffId());
            }
            Intent intent = new Intent();
            intent.putExtra(DefaultConsts.TEAM_ID_LIST, ids.toString());
            setResult(Activity.RESULT_OK, intent);
            finish();
        } else {
            Util.ToastShow(context, "请选择要添加的成员");
        }
    }

    private void create() {
        if (adapter.getSelectUids().size() > 0) {
            JSONArray uidsString = new JSONArray();
            StringBuilder teamName = new StringBuilder();
            for (int i = 0; i < adapter.getSelectUids().size(); i++) {
                String uidLong = adapter.getSelectUids().get(i).getStaffId();
                uidsString.put(uidLong);
                if (teamName.length() > 0 && i < 5) {
                    teamName.append(",");
                }
                teamName.append(Util.isEmpty(adapter.getSelectUids().get(i).getStaffName()) ? adapter.getSelectUids().get(i).getAccount() : adapter.getSelectUids().get(i).getStaffName());
            }
            NewActionHelp.createTeam(context, teamName.toString(), uidsString.toString(), "", "y", new CreateHandler());
            //			Util.ToastShow(context, teamName);
        } else {
            Util.ToastShow(context, "请选择至少一个群成员");
        }

    }

    private class CreateHandler
            extends
            TextHttpResponseHandler {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (statusCode > 1000) {
                try {
                    Util.ToastShow(context, JSONUtil.getString(responseString));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Util.ToastShow(context, "创建失败");
            }

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            try {

                Util.ToastShow(context, JSONUtil.getString(responseString));
                NewInteractionCreateTeamChMActivity.this.finish();
                setResult(RESULT_OK);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

}
